package com.ustb.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ustb.springboot.common.utils.R;
import com.ustb.springboot.common.utils.TokenUtil;
import com.ustb.springboot.entity.AnswerBlankEntity;
import com.ustb.springboot.entity.OptionEntity;
import com.ustb.springboot.entity.QuestionCheckboxEntity;
import com.ustb.springboot.service.OptionService;
import com.ustb.springboot.service.QuestionCheckboxService;
import org.apache.logging.log4j.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ustb.springboot.dao.AnswerCheckboxDao;
import com.ustb.springboot.entity.AnswerCheckboxEntity;
import com.ustb.springboot.service.AnswerCheckboxService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("answerCheckboxService")
public class AnswerCheckboxServiceImpl extends ServiceImpl<AnswerCheckboxDao, AnswerCheckboxEntity> implements AnswerCheckboxService {
    @Resource
    private AnswerCheckboxDao answerCheckboxDao;
    @Autowired
    AnswerCheckboxServiceImpl answerCheckboxService;
    @Autowired
    QuestionCheckboxService questionCheckboxService;
    @Autowired
    OptionService optionService;

    @Override
    public R delete(Map<String, Object> body) {
        QueryWrapper<AnswerCheckboxEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", body.get("id"));
        return answerCheckboxDao.delete(queryWrapper) == 1 ? R.ok(20000, "删除成功") : R.error(2000, "删除失败");
    }

    @Override
    public R save(HttpServletRequest request, Map<String, Object> body) {
        if (body == null || !body.containsKey("optionId"))
            return R.error("参数错误");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");


        String id = body.get("id").toString();//答案表id
        Integer userId = TokenUtil.getId(request);
        String formId = body.get("formId").toString();
        String questionId = body.get("questionId").toString();
        Boolean isSubmit = Boolean.getBoolean(body.get("isSubmit").toString());

        Date createTime;
        try {
            createTime = sdf.parse(body.get("createTime").toString());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        //获取optionId数组
        List<String> optionId = (List<String>) body.get("optionId");
        //创建多选数组
        Collection<AnswerCheckboxEntity> answerCheckboxEntities = new LinkedList<>();

        optionId.forEach(option ->
                answerCheckboxEntities.add(
                        new AnswerCheckboxEntity().setId(id)
                                .setUserId(userId)
                                .setFormId(formId)
                                .setQuestionId(questionId)
                                .setOptionId(option)
                                .setCreateTime(createTime)
                                .setIsSubmit(isSubmit)
                )
        );

        //存在id
        if (answerCheckboxDao.exists(new QueryWrapper<AnswerCheckboxEntity>().eq("id", id))) {
            answerCheckboxDao.delete(new QueryWrapper<AnswerCheckboxEntity>().eq("id", id));
        }
        return this.saveBatch(answerCheckboxEntities) ? R.ok(20000, "保存多选题答案成功！") : R.error(2000, "保存多选题答案失败！");


    }

    @Override
    public List<AnswerCheckboxEntity> queryCheckboxWithFormId(String formId) {
        QueryWrapper<AnswerCheckboxEntity> answerCheckboxDaoQueryWrapper = new QueryWrapper<>();
        answerCheckboxDaoQueryWrapper.eq("form_id",formId);
        List<AnswerCheckboxEntity> answerCheckboxEntityList = answerCheckboxDao.selectList(answerCheckboxDaoQueryWrapper);
        return answerCheckboxEntityList;
    }

    @Override
    public List<AnswerCheckboxEntity> queryCheckboxWithQuestionId(String QuestionId) {
        QueryWrapper<AnswerCheckboxEntity> answerCheckboxDaoQueryWrapper = new QueryWrapper<>();
        answerCheckboxDaoQueryWrapper.eq("question_id",QuestionId);
        List<AnswerCheckboxEntity> answerCheckboxEntityList = answerCheckboxDao.selectList(answerCheckboxDaoQueryWrapper);
        return answerCheckboxEntityList;
    }

    @Override
    public Map<String, Object> summerizeCheckboxMessage(Map<String,Object>body) {
       List<AnswerCheckboxEntity> checkboxEntityList = new ArrayList<>();

       checkboxEntityList = queryCheckboxWithQuestionId(body.get("question_id").toString());
       //查询到的checkbox列表
       Map<String , Object> summerizeMessages = new HashMap<>();
       Map <String,Map>TempSummerizeMessage = new HashMap<>();
       //汇总信息的列表
       Integer sum = 0;
       //计算所有的选择次数（用于计算百分比）
        List<OptionEntity> optionEntityList= optionService.queryWithId(body);
        sortByOrderId(optionEntityList,0,optionEntityList.size()-1);
        //System.out.println(optionEntityList);
        //获取选项信息
        List<String> Message = new ArrayList<>();
        for(OptionEntity optionEntity : optionEntityList){
            Message.add(optionEntity.getOrderId().toString());
            if (optionEntity.getContent().isEmpty() == false)
                Message.add(optionEntity.getContent());
            else
                Message.add("null");
            Message.add("0");
            Message.add("0");
        }
        System.out.println(Message);
        for(AnswerCheckboxEntity answerCheckboxEntity : checkboxEntityList){
            Integer num = Integer.parseInt(answerCheckboxEntity.getOptionId().toString());
            //System.out.println("num:"+num.toString());
            Integer index = (num - 1)*4 + 2;
            Integer newVal = Integer.parseInt(Message.get(index).toString()) + 1;
            Message.set(index,newVal.toString());
            sum++;
        }

        for (Integer i = 1;i<checkboxEntityList.size() / 4;i++){
            Integer index = (i - 1)*4 + 2;
            Integer num = Integer.parseInt(Message.get(index).toString());
            Float target = (num.floatValue()/sum.floatValue())*100;
            String Target = target.toString();
            Message.set(index+1,Target);
         }
        List<Map> structMessage = new ArrayList<>();

        for(int i = 0; i < Message.size() / 4 ; i++){
            Map<String,String> struct = new HashMap<>();
            struct.put("order_id",Message.get(i * 4 + 0));
            struct.put("order_information",Message.get(i * 4 + 1));
            struct.put("number",Message.get(i * 4 + 2));
            struct.put("percentage",Message.get(i * 4 + 3));
//            for(int j = 0; j < 4 ; j++){
//                struct.add(Message.get(i * 4 + j));
//            }
            structMessage.add(struct);
        }
       summerizeMessages.put("total_message",structMessage);
       return summerizeMessages;
    }
    private  Integer searchList(List<String> list , String target){
        Integer index = 0;
        for (Integer i = 0 ; i < list.size(); i++){
            String str = list.get(i);
            if (target.equals(str)){
                index = i;
                break;
            }
            index = -1;
        }
        return index;
    }
    private  void sortByOrderId(List<OptionEntity> list,Integer start,Integer end){
        if (start >= end) {
            return;
        }
        OptionEntity a =list.get(start);//定义基准值
        int i = start;//开始位置下标
        int j = end;//末尾位置下标
        while (i < j) {
            while (i<j && Integer.parseInt(list.get(j).getOrderId().toString())>=a.getOrderId()) {
                j--;
            }
            while (i<j && Integer.parseInt(list.get(i).getOrderId().toString())<=a.getOrderId()) {
                i++;
            }
            if (i<j) {//交换i和j的值
                Collections.swap(list,i,j);
//                int temp = arr[j];
//                arr[j] = arr[i];
//                arr[i] = temp;
            }
        }
        list.set(start,list.get(i));
        list.set(i,a);
        sortByOrderId(list, start, i-1);//递归调用
        sortByOrderId(list, i+1, end);
    }
}